#!/bin/bash


if [ -z "$3" ]; then
    TARGET=""
elif [ "$3" == "/" ]; then
    TARGET=""
else
    TARGET="$3"
fi

MRDIR="$TARGET/Library/MunkiReport"
SUPPORTDIR="$TARGET/Library/Application Support/MunkiReport"


# Create munkireport user if it doesn't exist.
DSNODE="${TARGET}/var/db/dslocal/nodes/Default"
DSCL="${TARGET}/usr/bin/dscl"
SHORTNAME="munkireport"
LONGNAME="MunkiReport"
HOME=/Library/MunkiReport
SHELL=/bin/bash
GID=20
USERROOT="/Local/Target/Users"
USERPATH="$USERROOT/$SHORTNAME"
uniqueid=`"$DSCL" -f "$DSNODE" localonly -read "$USERPATH" UniqueID 2>/dev/null`
if [ $? -eq 0 ]; then
    uid=`echo $uniqueid | awk '{print $2}'`
else
    STARTUID=501
    STOPUID=600 
    for (( uid=$STARTUID; uid<$STOPUID; uid++ )); do
    	output=`"$DSCL" -f "$DSNODE" localonly -search "$USERROOT" UniqueID $uid`
    	if [ "$output" == "" ]; then
    		break
    	fi
    done
    if [ $uid -eq $STOPUID ]; then
        echo "munkireport user creation failed: No free UID between $STARTUID and $STOPUID"
        exit 1
    fi

    echo "Creating $USERPATH with name '$LONGNAME' gid $GID UniqueID $uid home $HOME in '$DSNODE'"
    "$DSCL" -f "$DSNODE" localonly -create "$USERPATH" || exit 1
    "$DSCL" -f "$DSNODE" localonly -create "$USERPATH" realname "$LONGNAME"
    "$DSCL" -f "$DSNODE" localonly -create "$USERPATH" gid $GID
    "$DSCL" -f "$DSNODE" localonly -create "$USERPATH" UniqueID $uid
    "$DSCL" -f "$DSNODE" localonly -create "$USERPATH" home "$HOME"
    "$DSCL" -f "$DSNODE" localonly -merge  "$USERPATH" authentication_authority ";ShadowHash;"
    "$DSCL" -f "$DSNODE" localonly -create "$USERPATH" passwd "*"
    "$DSCL" -f "$DSNODE" localonly -create "$USERPATH" shell "$SHELL"

    /usr/bin/defaults write "${TARGET}/Library/Preferences/com.apple.loginwindow" HiddenUsersList -array-add $SHORTNAME
fi


# Create and populate Application Support directory if needed.
if [ -d "$SUPPORTDIR" ]; then
    true # TODO: Database backup/schema migration.
else
    mkdir -m 0775 "$SUPPORTDIR"
    mkdir -m 0775 "$SUPPORTDIR"/Cache
    mkdir -m 0775 "$SUPPORTDIR"/Logs
    
    # Create users, groups, and permissions
    cat > "$SUPPORTDIR/permissions.ini" <<EOF
[admin]
admins

[view]
viewers
EOF
    
    cat > "$SUPPORTDIR/groups.ini" <<EOF
[admins]
munkiadmin

[viewers]
munkiadmin
EOF
    
    
    # Create MunkiReport.ini
    echo "* Creating $SUPPORTDIR/MunkiReport.ini"
    perl -e '
        $uuid = `uuidgen`;
        foreach $line (<>) {
            $line =~ s/^#(.+)SET SECRET STRING HERE/$1$uuid/;
            print $line
        }
    ' < "$MRDIR/MunkiReport.ini.template" > "$SUPPORTDIR/MunkiReport.ini"
    
    # Set ownership and modes.
    find "$SUPPORTDIR" -print0 | xargs -0 chmod ug+rw,o-w
    chown -hR ${uid}:admin "$SUPPORTDIR"
fi


# Start LaunchDaemon if we're installing on a live system.
if [ -z "$TARGET" ]; then
    launchctl load -w /Library/LaunchDaemons/com.googlecode.munkireport.plist
fi


exit 0
